package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.AddressMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrdersServiceImpl implements OrdersService {
    private final OrdersMapper ordersMapper;
    private final AddressMapper addressMapper;
    private final ShoppingCartMapper shoppingCartMapper;
    private final WebSocketServer webSocketServer;

    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        List<OrderVO> ordersList = ordersMapper.getOrdersList(ordersPageQueryDTO.getStatus(), BaseContext.getCurrentId());
        ordersList.forEach(orderVO -> {
            List<OrderDetail> orderDetailList = ordersMapper.selectByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetailList);
        });
        PageInfo<OrderVO> ordersPageInfo = PageInfo.of(ordersList);
        return new PageResult(ordersPageInfo.getTotal(), ordersPageInfo.getList());
    }

    @Override
    public OrderVO getOrdersById(String id) {
        OrderVO orders = ordersMapper.getOrdersById(id);
        List<OrderDetail> orderDetailList = ordersMapper.getOrderDetailById(id);
        orders.setOrderDetailList(orderDetailList);
        return orders;
    }

    @Override
    public void getReminderById(Long id) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("type", 1);
        params.put("orderId", id);
        params.put("content", "订单Id：" + id);
        webSocketServer.sendToAllClient(JSON.toJSONString(params));
    }

    @Override
    public void getRepetitionById(String id) {
        List<OrderDetail> orderDetailList = ordersMapper.getByUserId(id);
        orderDetailList.forEach(orderDetails -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetails, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.addShoppingCart(shoppingCart);
        });
    }

    @Override
    @Transactional
    public void getCancelById(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        ordersMapper.deleteById(orders);
    }

    @Override
    public OrderSubmitVO insertSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        AddressBook addressBook = addressMapper.getAddressById(ordersSubmitDTO.getAddressBookId(), BaseContext.getCurrentId());
        String addressName = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        String numId = UUID.randomUUID().toString();
        orders.setNumber(numId);
        orders.setAddress(addressName);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setCancelTime(LocalDateTime.now());
        orders.setOrderTime(LocalDateTime.now());
        ordersMapper.insertSubmit(orders);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.getByUserId(BaseContext.getCurrentId());
        shoppingCarts.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            ordersMapper.insertOrderDetail(orderDetail);
        });
        shoppingCartMapper.deleteShoppingCart(BaseContext.getCurrentId());
        return ordersMapper.selectOrder(numId, BaseContext.getCurrentId());
    }

    @Override
    public void paySuccess(String number) {
        Orders order = new Orders();
        order.setNumber(number);
        order.setStatus(Orders.TO_BE_CONFIRMED);
        order.setCheckoutTime(LocalDateTime.now());
        order.setPayStatus(1);
        ordersMapper.updateByNumber(order);
        Orders orders = ordersMapper.selectByNumber(number);
        HashMap<String, Object> params = new HashMap<>();
        params.put("type", 1);
        params.put("orderId", orders.getId());
        params.put("content", "订单号：" + number);
        webSocketServer.sendToAllClient(JSON.toJSONString(params));

    }
}
